package org.jgs2007.onemall.interceptor;

import org.jgs2007.onemall.annotation.LoginInterceptorIgnore;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器，登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){

        // 判断是否需要拦截
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            LoginInterceptorIgnore methodAnnotation = handlerMethod.getMethod().getAnnotation(LoginInterceptorIgnore.class);
            if (methodAnnotation != null) {
                return true;
            }
        }

        // 判断token
        String token = request.getHeader("token");
        if (token == null) {
            throw new RuntimeException("还未登录！");
        } else {
            return true;
        }
    }
}
